package com.mrjy.maintain.bo;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.mrjy.common.entity.MessageInfo;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.entity.UserMemberInfo;
import com.mrjy.common.util.DateUtil;
import com.mrjy.maintain.dao.IGradeInfoDao;
import com.mrjy.maintain.dao.IMessageInfoDao;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.maintain.dao.IUserMemberInfoDao;
import com.mrjy.payment.dao.IUserBalancePaymentDao;
import com.mrjy.share.dao.IDistributorInfoDao;
import com.mrjy.share.dto.DistributorInfoDTO;
import com.mrjy.wechat.conts.WxConsts;
import com.mrjy.wechat.util.WeChatUtil;

@Service("userMemberInfoBo")
public class UserMemberInfoBo implements IUserMemberInfoBo {

	@Resource
	private IUserMemberInfoDao userMemberInfoDao;
	@Resource
	private IUserInfoDao userInfoDao;
	@Resource
	private IUserBalancePaymentDao userBalancePaymentDao;
	@Resource
	private IGradeInfoDao gradeInfoDao;
	@Resource
	private IMessageInfoDao messageInfoDao;
	@Resource
	private IDistributorInfoDao distributorInfoDao;
	
	@Override
	public String addMemberInfo(UserMemberInfo userMemberInfo) {
		userMemberInfoDao.insert(userMemberInfo);
		return "ok";
	}

	@Override
	public String updateMemberInfo(UserMemberInfo userMemberInfo) {
		userMemberInfoDao.updateById(userMemberInfo);
		return "ok";
	}

	/**
	 * 定时器调用方法
	 */
	@Override
	public Object txCheckUserMemberExpired() {
		Map<String , Object> map = new HashMap<String, Object>();
		//1.先检查会员过期的记录，并将会员状态membership_flag=1 改成 临时状态membership_flag=2
		userMemberInfoDao.checkUserMemberExpired();
		//2.查出刚刚过期的记录，并添加提醒消息
		List<UserMemberInfo> userMemberInfos = userMemberInfoDao.getUserMemberExpired();
		if(null == userMemberInfos || userMemberInfos.size() == 0){
			map.put("err_code",1);
			map.put("err_msg", "没有过期会员的数据");
		}else{
			for (UserMemberInfo userMemberInfo:userMemberInfos) {
				MessageInfo messageInfo = new MessageInfo();
				messageInfo.setTitle("会员到期信息");
				
				messageInfo.setContent("您购买的365家长课堂VIP会员已经到期，如想继续免费观看所有微课");
				messageInfo.setSendTime(new Date());
				messageInfo.setSenderId(1);
				messageInfo.setUserId(userMemberInfo.getUserId());
				messageInfo.setReadTag(0);
				messageInfo.setMsgModule(2);
				messageInfo.setEndTime(new Timestamp(userMemberInfo.getEndDate()));
				messageInfoDao.insert(messageInfo);
			}
			//3.把临时状态为2的修改为0，变成非会员
			int count = userMemberInfoDao.setUserMemberExpired();
			map.put("err_code",0);
			map.put("err_msg", "已向"+  count  +"位用户发送会员到期提醒");
		}	
		
		return map;
	}
	/**
	 * 定时器调用方法
	 */
	@Override
	public Object checkUserBalanceWillExpire(int numDate) {
		Map<String,Object> map = new HashMap<String,Object>();
		//1.查询离会员过期还有numDate天的记录，并添加我的消息提醒
		List<UserMemberInfo> userMemberInfos = userMemberInfoDao.getUserBalanceWillExpire(numDate);
		if(null == userMemberInfos || userMemberInfos.size() == 0){
			map.put("err_code",1);
			map.put("err_msg", "没有离过期还有" + numDate + "天的数据");
		}else{
			for (UserMemberInfo userMemberInfo : userMemberInfos) {
				MessageInfo messageInfo = new MessageInfo();
				messageInfo.setTitle("会员即将到期");
				messageInfo.setContent("您购买的365家长课堂VIP会员已经即将到期（"+ DateUtil.longToString(userMemberInfo.getEndDate(), DateUtil.FULL_DATE)  +" 到期），如想继续免费观看所有微课");
				messageInfo.setSendTime(new Date());
				messageInfo.setSenderId(1);
				messageInfo.setUserId(userMemberInfo.getUserId());
				messageInfo.setReadTag(0);
				messageInfo.setMsgModule(2);
				messageInfo.setEndTime(new Timestamp(userMemberInfo.getEndDate()));
				messageInfoDao.insert(messageInfo);
			}
			map.put("err_code",0);
			map.put("err_msg", "已向"+  userMemberInfos.size()  +"位用户发送会员即将到期提醒");
		}
		
		return map;
	}
	/**
	 * 根据用户id查询是否为vip
	 */
	@Override
	public Object isVip(UserMemberInfo info) {
		Map<String,Object> map = new HashMap<String,Object>();
		if(null == info.getUserId() || "".equals(info.getUserId().toString())){
			map.put("err_code", -1);
			map.put("err_msg", "没有userID");
		}
		double sharingProportion = 0.1;
		DistributorInfoDTO loginUser = distributorInfoDao.queryByUserId(info.getUserId());
		if (loginUser != null) {
			sharingProportion = loginUser.getSharingProportion();
			map.put("sharingProportion", sharingProportion);
        } else {
            map.put("sharingProportion", sharingProportion);
        }
        map.put("divideMoney", 365*sharingProportion);
		UserMemberInfo userMemberInfo = userMemberInfoDao.selectIsVipByUserId(info.getUserId());
		if (null != userMemberInfo  ) {
			map.put("err_code", 0);
			map.put("err_msg", "会员");
			map.put("userMemberInfo", userMemberInfo);
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "非会员");
		}
		return map;
	}

	@Override
	public Object checkUserBalanceWillExpire3Day(int numDate) {
		Map<String,Object> map = new HashMap<String,Object>();
		//1.查询离会员过期还有numDate天的记录，并添加我的消息提醒
		List<UserMemberInfo> userMemberInfos = userMemberInfoDao.getUserBalanceWillExpire(numDate);
		if(null == userMemberInfos || userMemberInfos.size() == 0){
			map.put("err_code",1);
			map.put("err_msg", "没有离过期还有" + numDate + "天的数据");
		}else{
			UserInfo ui = null ;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for (UserMemberInfo userMemberInfo : userMemberInfos) {
				MessageInfo messageInfo = new MessageInfo();
				messageInfo.setTitle("会员即将到期");
				messageInfo.setContent("您购买的365家长课堂VIP会员已经即将到期（"+ DateUtil.longToString(userMemberInfo.getEndDate(), DateUtil.FULL_DATE)  +" 到期），如想继续免费观看所有微课");
				messageInfo.setSendTime(new Date());
				messageInfo.setSenderId(1);
				messageInfo.setUserId(userMemberInfo.getUserId());
				messageInfo.setReadTag(0);
				messageInfo.setMsgModule(2);
				messageInfoDao.insert(messageInfo);
				
				if(userMemberInfo.getUserId() != null){
					ui = userInfoDao.queryById(userMemberInfo.getUserId());
					if(ui != null && StringUtils.isNotBlank(ui.getWeixinOpenid())){
						WeChatUtil.sendWechatTemplateMessageExpireVip(sdf.format(userMemberInfo.getEndDate())
								, WxConsts.PUBLIC_DOMAIN + "/index.html?from=weInfo/vip_center.html" , ui.getWeixinOpenid());
					}
				}
				
			}
			map.put("err_code",0);
			map.put("err_msg", "已向"+  userMemberInfos.size()  +"位用户发送会员即将到期提醒");
		}
		
		return map;
	}

}
